require 'View/UIBase/UIBase'

UIBornGiftSpecial = UIBase.New(PanelResNames.UIBornGiftSpecial)

function UIBornGiftSpecial.Init(func, id)
    UIBornGiftSpecial.activeId = id;
    UIBase.Init(UIBornGiftSpecial,func);
end

-- 创建回调
function UIBornGiftSpecial:OnCreate()
    --AddUIPackageDepend(PanelResNames.UIBornGiftSpecial,"FUI/BusinessAtlas")
    self.drawWrapper = GoWrapper.New()
    self.countDownNum = 0;

    self.bg = self:GetChild("bg");
    self.countDown = self:GetChild("countDown");
    self.buyBtn = self:GetChild("buy");
    self.title = self:GetChild("title");
    self.fristItem = self:GetChild("fristItem");
    self.itemList = {};
    for i = 1, 5 do
        local item = self:GetChild("item"..i);
        table.insert(self.itemList, item);
    end
    self:addEvent();
end

-- 显示
function UIBornGiftSpecial:OnEnable()
    if self.activeId == nil then
        self:OnBack();
    else
        self:Refresh();
    end
end

function UIBornGiftSpecial:addEvent()
    self:RegisterOnClick(self:GetChild("bgClose"),self.OnClose);
    self:RegisterOnClick(self:GetChild("buy"),self.OnBuy);
end

function UIBornGiftSpecial:removeEvent()
end

function UIBornGiftSpecial:Refresh()
    self:UpdateData();
end

function UIBornGiftSpecial:UpdateData()
    local severData, itemsTable, modelTableData = logicMgr.CostManager.getCostData(self.activeId);
    if #severData > 0 then
        self.itemSeverData = severData[#severData];
    else
        self:OnClose();
        return ;
    end
    local itemTable = itemsTable[tostring(self.itemSeverData.subId)];
    self.bg.url = tostring(modelTableData.f_BannerHead);
    self.title.text = getLanguage(modelTableData.f_Title, nil, "");
    if itemTable.f_Price == 0 then
        self.buyBtn.title = getLanguage("FreeMoney");
    else
        self.buyBtn.title = "￥"..itemTable.f_Price;
    end
    self.cheekItemMoney = itemTable.f_Price;
    self.payId = itemTable.f_ProductId;
    logicMgr.CostManager.RefreshItem(self.fristItem, decodeJsonStrToTabel(itemTable.f_MajorCommodityReward)[1]);
    local reward = decodeJsonStrToTabel(itemTable.f_CommonCommodityReward);
    for k, v in pairs(self.itemList) do
        if reward[k] ~= nil then
            logicMgr.CostManager.RefreshItem(v, reward[k]);
            v.visible = true;
        else
            v.visible = false;
        end
    end

    self:RemoveAllTimeCall();
    self.countDown.visible = false;
end

--- 购买
function UIBornGiftSpecial:OnBuy()
    logicMgr.CostManager.getRewardByIdAndIndex(self.activeId, self.itemSeverData.subId, self.payId, 1, self.cheekItemMoney, self.onBuySuccess, self);
end

-- 购买成功
function UIBornGiftSpecial:onBuySuccess()
    self:OnClose();
end

-- 关闭
function UIBornGiftSpecial:OnClose()
    self:OnBack();
    logicMgr.CostManager.showPopUpTips();
    self:RemoveAllTimeCall();
end

-- 隐藏
function UIBornGiftSpecial:OnDisable()
end

-- 卸载
function UIBornGiftSpecial:OnDestroy()
    self:removeEvent();
end

return UIBornGiftSpecial